import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  // token
  const userToken = ref(localStorage.getItem('token') || '')
  const adminToken = ref(localStorage.getItem('adminToken') || '')
  // 用户与管理员信息（可选）
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))
  const adminInfo = ref(JSON.parse(localStorage.getItem('adminInfo') || 'null'))
  const adminPermissions = ref(JSON.parse(localStorage.getItem('adminPermissions') || '[]'))

  const isUserLoggedIn = computed(() => !!userToken.value && userToken.value.trim() !== '')
  const isAdminLoggedIn = computed(() => !!adminToken.value && adminToken.value.trim() !== '')

  function setUserToken(token) {
    userToken.value = token || ''
    if (userToken.value) {
      localStorage.setItem('token', userToken.value)
    } else {
      localStorage.removeItem('token')
    }
  }

  function setAdminToken(token) {
    adminToken.value = token || ''
    if (adminToken.value) {
      localStorage.setItem('adminToken', adminToken.value)
    } else {
      localStorage.removeItem('adminToken')
    }
  }

  function setUserInfo(info) {
    userInfo.value = info || null
    if (info) {
      localStorage.setItem('userInfo', JSON.stringify(info))
    } else {
      localStorage.removeItem('userInfo')
    }
  }

  function setAdminInfo(info) {
    adminInfo.value = info || null
    if (info) {
      localStorage.setItem('adminInfo', JSON.stringify(info))
    } else {
      localStorage.removeItem('adminInfo')
    }
  }

  function setAdminPermissions(perms) {
    const arr = Array.isArray(perms) ? perms : []
    adminPermissions.value = arr
    if (arr.length > 0) {
      localStorage.setItem('adminPermissions', JSON.stringify(arr))
    } else {
      localStorage.removeItem('adminPermissions')
    }
  }

  function hasPermission(perm) {
    // 所有管理员权限相同，只要登录就拥有所有权限
    return isAdminLoggedIn.value
  }

  function logoutUser() {
    setUserToken('')
    setUserInfo(null)
  }

  function logoutAdmin() {
    setAdminToken('')
    setAdminInfo(null)
    setAdminPermissions([])
  }

  return {
    userToken,
    adminToken,
    userInfo,
    adminInfo,
    adminPermissions,
    isUserLoggedIn,
    isAdminLoggedIn,
    setUserToken,
    setAdminToken,
    setUserInfo,
    setAdminInfo,
    setAdminPermissions,
    logoutUser,
    logoutAdmin,
    hasPermission
  }
})


